<?php

namespace app\order\logic;

use app\common\library\Excel;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use app\order\logic\OrderLogic;
use think\facade\Config;
use Throwable;
use app\order\model\Order as OrderModel;
use think\facade\Db;


class OrderDocumentLogic
{



    protected $model = null;

    public function __construct()
    {
        $this->model = new OrderModel();
    }

    /**
     * @desc  列表
     * @date  2024/3/21 0021
     * @param $params
     * @return \think\response\Json
     * @author ligang
     */
    public function getTkOrderList($params = [])
    {

        $orderId         = $params['order_id'] ?? '';
        $status          = $params['status'] ?? '';
        $seller_sku      = $params['skus_info'] ?? '';
        $tracking_number = $params['tracking_number'] ?? '';
        $shop_id         = $params['shop_id'] ??'';
        $limit           = $params['limit'] ?? 10;

        $where = [];
        $where[]  = ['shipping_type', '=', 'TIKTOK'];

        if ($orderId) {
            $order_ids = trim($orderId);
            $order_ids = array_filter(array_map('trim', explode("\n", $order_ids)));
            if (!empty($order_ids)) {
                $where[] = ['order_id', 'in', $order_ids];
            }
        }


        if ($status){
            switch ($status) {
                case 'create_waybill_currently':
                    $where[] = ['shipping_documents_status', '=', 1];
                    break;
                case 'create_waybill_successfully':
                    $where[] = ['shipping_documents_status', '=', 4];
                    break;
                case 'create_waybill_failed':
                    $where[] = ['shipping_documents_status', '=', 3];
                    $where[] = ['shipping_documents', '=', ''];
                    break;
                case 'create_waybill_failed_pdf':
                    $where[] = ['shipping_documents_status', '=', 5];
                    break;
                case 'waybill_processed':
                    $where[] = ['shipping_documents_status', '=', 6];
                    break;
                default:
                    $where[] = ['status', '=', 'AWAITING_SHIPMENT'];
                    $where[] = ['shipping_documents_status', '=', 0];
                    break;
            }
        }else{
            $wait_status = ['AWAITING_SHIPMENT'];
            $where[] = ['status', 'in', $wait_status];
            $where[] = ['shipping_documents_status', '=', 0];
        }

        if ($seller_sku) {
            $orderIds = Db::name('order_info')
                ->where('seller_sku', 'like', '%' . $seller_sku . '%')
                ->column('order_id');
            $orderIds = array_unique($orderIds);
            if (count($orderIds)) {
                $where[] = ['order_id', 'in', $orderIds];
            }
        }
        if ($tracking_number) {
            $where[] = ['tracking_number', 'like', '%' . $tracking_number . '%'];
        }
        if ($shop_id) {
            $where[] = ['shop_id', '=', $shop_id];
        }

        $field = ['id','order_id','shop_id','createtime','shipping_type','createtime',
                'tracking_number', 'shipping_documents','shipping_documents_status','status'
                ];

        $res = Db::name('order')
            ->where($where)
            ->field($field)
            ->order(['createtime' => 'desc', 'id' => 'desc'])
            ->paginate($limit);

        $list      = $res->items()?:[];

        $shop_ids  = array_column($list,'shop_id');
        $shop_ids  = array_values(array_unique($shop_ids));

        $order_ids = array_column($list,'order_id');
        $order_ids = array_values(array_unique($order_ids));


        //批量获取店铺信息及sku数量信息;
        $shopInfos     = Db::name('shops')->whereIn('id',$shop_ids)->field('name,id')->select();
        $shopInfos     = objectToArray($shopInfos);
        $shopInfos_map = array_column($shopInfos,null,'id');

        //批量获取sku数量数据;
        $skuInfos     = Db::name('order_info')->whereIn('order_id',$order_ids)->field('seller_sku,order_id')->select();
        $skuInfos     = objectToArray($skuInfos);
        $skuInfos_map = (new OrderLogic())->get_sku_info($skuInfos);

        if($list){
            foreach($list as $k=>$v){
                $shop_names = $shopInfos_map[$v['shop_id']]??[];
                $sku_names = $skuInfos_map[$v['order_id']]??[];
                $list[$k]['shop_name']     =  $shop_names['name']??'';
                $list[$k]['skus_info']     =  $sku_names ? implode(',',$sku_names):'';
            }
        }



        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    public function editTkOrderList($project, $data)
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }

        $result = false;
        $this->model->startTrans();
        try {
            $result = $project->save($data);
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            return json(DefaultResponse(201, false, $e->getMessage(), null));
        }
        if ($result !== false) {
            return json(DefaultResponse(200, true, '更新成功!', null));
        } else {
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
    }


    /**
     * @desc  批量创建面单
     * @date  2024/3/21 0021
     * @param $params
     * @return \think\response\Json
     * @author ligang
     */
    public function createShippingDocuments($params = [])
    {

        $ids   = $params['ids'];
        htmlLog(['params'=>$params],OPERATE_LOG . date('Ym') . '/createShippingDocuments/' . date('Ymd') . '.txt');
        $ids   = is_array($ids) ? $ids : explode(',', $ids);
        $items = Db::name('order')->whereIn('id', $ids)->select();
        $items = objectToArray($items);
        if(empty($items))  return json(DefaultResponse(201, false, '暂无创建面单数据!', null));
        //创建批次
        $bach_id = Db::name('order_shipping_documents')->insertGetId(
            [
                'num'          =>count($items),
                'created_time' =>date("Y-m-d H:i:s", time()),
            ]);
        $already_arr = $first_arr = $update_ids = $que_message = [];
        foreach ($items as $v){
               if(in_array($v['shipping_documents_status'],[2,4])){//已创建面单或生成pdf
                   $already_arr[] = [
                       'batch_id'      =>$bach_id,
                       'order_id'      =>$v['order_id'],
                       'shop_id'       =>$v['shop_id'],
                       'status'        =>2,
                       'msg'           =>"已创建面单",
                       'created_time'  => date("Y-m-d H:i:s", time()),
                   ];
               }else{
                   $first_arr[] = [
                       'batch_id'      =>$bach_id,
                       'order_id'      =>$v['order_id'],
                       'shop_id'       =>$v['shop_id'],
                       'status'        =>1,
                       'msg'           =>"创建中",
                       'created_time'  => date("Y-m-d H:i:s", time()),
                   ];
                   $update_ids[] = $v['id'];
                   $que_message = [
                       'batch_id'      =>$bach_id,
                       'order_id'      =>$v['order_id'],
                       'shop_id'       =>$v['shop_id'],
                       ];
                   // 队列处理
                   MqTaskPushLogic::mq_task_push(
                       '',
                       MqQueueName::CREATE_TK_ORDER_DOCUMENT_QUEUE,
                       $que_message,
                       false
                   );
               }
        }

        //批量处理数据;
        if($already_arr){
            Db::name('order_shipping_documents_log')->insertAll($already_arr);
        }

        if($first_arr){
            Db::name('order_shipping_documents_log')->insertAll($first_arr);
        }

        if($update_ids){
            Db::name('order')->whereIn('id',$update_ids)->update(
                ['shipping_documents_status' =>1]
            );
        }

        //直接触发MQ消费 2024-05-14
       // (new OrderBtLogic())->getCrontab();

        return json(DefaultResponse(200, true, '操作成功!'));
    }

    /**
     * @desc  订单-标记成已处理
     * @date  2024/3/21 0021
     * @param $params
     * @author ligang
     */
    public function markerOrderDocument($params = [])
    {
        $ids   = $params['ids'];
        $ids   = is_array($ids) ? $ids : explode(',', $ids);
        Db::name('order')
            ->whereIn('id', $ids)
            ->update(
                ['shipping_documents_status' => 6]
            );
        return json(DefaultResponse(200, true, '操作成功!'));
    }

    /**
     * @desc  订单导出
     * @date  2024/3/21 0021
     * @param $params
     * @return bool
     * @author ligang
     */
    public function exportOrder($params = [])
    {

        $orderId         = $params['order_id'] ?? '';
        $status          = $params['status'] ?? '';
        $seller_sku      = $params['skus_info'] ?? '';
        $shop_id         = $params['shop_name_arr'] ?? 0;

        $where   = [];
        $where[] = ['shipping_type', '=', 'TIKTOK'];



        if ($orderId) {
            $order_ids = trim($orderId);
            $order_ids = array_filter(array_map('trim', explode("\n", $order_ids)));
            if (!empty($order_ids)) {
                $where[] = ['order_id', 'in', $order_ids];
            }
        }

        if ($status){
            switch ($status) {
                case 'create_waybill_currently':
                    $where[] = ['shipping_documents_status', '=', 1];
                    break;
                case 'create_waybill_successfully':
                    $where[] = ['shipping_documents_status', '=', 4];
                    break;
                case 'create_waybill_failed':
                    $where[] = ['shipping_documents_status', '=', 3];
                    break;
                case 'create_waybill_failed_pdf':
                    $where[] = ['shipping_documents_status', '=', 5];
                    break;
                case 'waybill_processed':
                    $where[] = ['shipping_documents_status', '=', 6];
                    break;
                default:
                    $where[] = ['status', '=', 'AWAITING_SHIPMENT'];
                    $where[] = ['shipping_documents_status', '=', 0];
                    break;
            }
        }else{
            $where[] = ['status', '=', 'AWAITING_SHIPMENT'];
            $where[] = ['shipping_documents_status', '=', 0];
        }

        if ($seller_sku) {
            $orderIds = Db::name('order_info')
                ->where('seller_sku', 'like', '%' . $seller_sku . '%')
                ->column('order_id');
            $orderIds = array_unique($orderIds);
            if ($orderIds) {
                $where[] = ['order_id', 'in', $orderIds];
            }
        }

        if ($shop_id) {
            $where[] = ['shop_id', '=', $shop_id];
        }

        $field = ['id','order_id','shop_id','shipping_type','createtime',
            'tracking_number', 'shipping_documents','shipping_documents_status'
        ];

        $list = Db::name('order')
            ->where($where)
            ->field($field)
            ->select();

        $list = objectToArray($list);

        if(!$list) return json(DefaultResponse(201, false, '暂无数据!'));
        $shop_ids     = array_column($list,'shop_id');
        $order_ids    = array_column($list,'order_id');
        //批量获取店铺信息及sku数量信息;
        $shopInfos     = Db::name('shops')->whereIn('id',$shop_ids)->field('name,id')->select();
        $shopInfos     = objectToArray($shopInfos);
        $shopInfos_map = array_column($shopInfos,null,'id');
        //批量获取sku数量数据;
        $skuInfos     = Db::name('order_info')->whereIn('order_id',$order_ids)->field('seller_sku,order_id')->select();
        $skuInfos     = objectToArray($skuInfos);
        $skuInfos_map = (new OrderLogic())->get_sku_info($skuInfos);
        foreach($list as $k=>$v){
            $shop_names = $shopInfos_map[$v['shop_id']]??[];
            $sku_names = $skuInfos_map[$v['order_id']]??[];
            $list[$k]['shop_name_arr'] =  $shop_names['name']??'';
            $list[$k]['skus_info']     =  $sku_names ? implode(',',$sku_names):'';
            $list[$k]['createtime']    =  $v['createtime'] ? date('Y-m-d H:i:s', $v['createtime']):'';
        }

        $header[] = ['店铺', 'shop_name_arr'];
        $header[] = ['订单号', 'order_id'];
        $header[] = ['SKU详情', 'skus_info'];
        $header[] = ['创建时间(美国)', 'createtime'];
        $fileName = "export_orderdocuments_order" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    /**
     * @desc  获取日志详情接口
     * @date  2024/4/16
     * @author
     */
    public function getLogInfo($order=[]){
        $order_id  = $order['order_id']??'';
        $list      = Db::name('order_shipping_documents_log')->where('order_id',$order_id)->field('id,order_id,status,msg,package_id,shipping_documents,created_time')->order('created_time desc')->select();
        $list      = objectToArray($list);
        $document_status = Config('Logisticskey.documents_status');
        foreach($list as $k=>$v){
            $list[$k]['status_value']         = $document_status[$v['status']]??'';
            $list[$k]['shipping_documents']   = $v['shipping_documents']??'';
            $msgInfo                          = $v['package_id'] ? json_decode($v['package_id'],true):[];
            $msg                              = $msgInfo['message']??'';
            $list[$k]['msg']                  = $msg ? :$v['package_id'];
            unset($list[$k]['package_id']);
        }
        return   json(DefaultResponse(200, true,'获取成功',$list ));
    }


    /**
     * @desc  获取日志详情接口
     * @date  2024/4/16
     * @author
     */
    public function get_row($id=''){
        $field = [
             'id','order_id','order.shop_id','createtime',
             'shipping_type','tracking_number','shipping_documents',
         ];

        $list = Db::name('order')
            ->where(['id'=>$id])
            ->field($field)
            ->find();
        $list['shop_name_arr'] =  Db::name('shops')->where('id',$list['shop_id'])->value('name');
        $sku_names             =  Db::name('order_info')->where('order_id',$list['order_id'])->column('seller_sku');
        $list['skus_info']     =  $sku_names ? implode(',',$sku_names):'';
        return $list;
    }


    /**
     * @desc  获取批次列表
     * @date  2024/4/18
     * @author luckyXiong
     */
    public function getBatchList(){
        $field = [
            'id','num','created_time'
        ];
        $list = Db::name('order_shipping_documents')
            ->field($field)
            ->order('id desc')
            ->limit(0, 20)
            ->select();
        return json(DefaultResponse(200, true,'获取成功', objectToArray($list)));
    }


    /**
     * @desc  获取批次日志
     * @date  2024/4/18
     * @author luckyXiong
     */
    public function getBatchLog($params = []){
        $batch_id = $params['batch_id']??'';
        $limit    = $params['limit'] ?? 10;
        $p        = $params['p'] ?? 1;
        $query    = "
                       SELECT
                            t1.*
                        FROM
                            ba_order_shipping_documents_log t1
                        JOIN (
                            SELECT
                                order_id,
                                MAX(created_time) AS max_date
                            FROM
                                ba_order_shipping_documents_log
                            WHERE
                                 batch_id = :batch_id
                            GROUP BY
                                order_id
                        ) t2 ON t1.order_id = t2.order_id
                        AND t1.created_time = t2.max_date
                        LIMIT :offset, :limit;
                       ";

        $list = Db::query($query, [
            'batch_id'  => $batch_id,
            'offset'    => ($p - 1) * $limit,
            'limit'     => $limit
        ]);

        //获取总量
        $total =  Db::name('order_shipping_documents_log')
            ->where('batch_id', $batch_id)
            ->group('order_id')
            ->count();

        $document_status = Config('Logisticskey.documents_status');
        foreach($list as $k=>$v){
            $list[$k]['status_value']        = $document_status[$v['status']]??'';
            $list[$k]['shipping_documents']  = $v['shipping_documents']??'';
        }
        $data = [
            'list'   => $list,
            'total'  => $total,
        ];
        return   json(DefaultResponse(200, true,'获取成功',$data ));
    }


    /**
     * @desc  导出获取批次日志
     * @date  2024/4/18
     * @author luckyXiong
     */
    public function exportLog($params = []){
        $batch_id = $params['batch_id']??'';
        $list = Db::name('order_shipping_documents_log')
            ->where('batch_id',$batch_id)
            ->select();
        $list =  objectToArray($list);
        $document_status = Config('Logisticskey.documents_status');
        foreach($list as $k=>$v){
            $list[$k]['status_value']  = $document_status[$v['status']]??'';
        }

        $header[] = ['订单ID', 'order_id'];
        $header[] = ['状态', 'status_value'];
        $header[] = ['面单地址', 'shipping_documents'];
        $header[] = ['返回消息', 'msg'];
        $header[] = ['添加时间', 'created_time'];
        $fileName = "export_orderdocuments_log" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }


}
